import os
import shutil
from pathlib import Path

ORIGINAL_DIR = r"S:\orignV"
COMPRESSED_DIR = r"S:\compressedV"
SCAN_DIR = r"S:\\"


def ensure_dirs():
    os.makedirs(ORIGINAL_DIR, exist_ok=True)
    os.makedirs(COMPRESSED_DIR, exist_ok=True)


def is_compressed(name: str) -> bool:
    return name.lower().endswith('_compressed.mp4')


def move_videos():
    ensure_dirs()
    moved_original = 0
    moved_compressed = 0
    skipped = 0
    conflicts = 0

    for p in Path(SCAN_DIR).glob('*.mp4'):
        try:
            name = p.name
            if is_compressed(name):
                target = Path(COMPRESSED_DIR) / name
            else:
                target = Path(ORIGINAL_DIR) / name

            if target.exists():
                # keep existing; avoid overwrite
                conflicts += 1
                continue

            shutil.move(str(p), str(target))
            if is_compressed(name):
                moved_compressed += 1
            else:
                moved_original += 1
        except Exception:
            skipped += 1

    return {
        'moved_original': moved_original,
        'moved_compressed': moved_compressed,
        'conflicts': conflicts,
        'skipped': skipped
    }


def update_missing_lists():
    # Rewrite tools/missing_videos_all.txt to point originals to S:\orignV and drop compressed entries
    src = Path('tools/missing_videos_all.txt')
    dst = Path('tools/missing_videos_originals.txt')
    if not src.exists():
        return None
    lines = [l.strip() for l in src.read_text(encoding='utf-8').splitlines() if l.strip()]
    out = []
    for line in lines:
        base = Path(line).name
        if is_compressed(base):
            # drop compressed from missing list
            continue
        candidate = Path(ORIGINAL_DIR) / base
        if candidate.exists():
            out.append(str(candidate))
    dst.write_text("\n".join(out), encoding='utf-8')
    return {'written': len(out), 'path': str(dst)}


if __name__ == '__main__':
    stats = move_videos()
    print(f"原始视频移动: {stats['moved_original']} / 压缩视频移动: {stats['moved_compressed']} / 冲突(已存在): {stats['conflicts']} / 跳过: {stats['skipped']}")
    upd = update_missing_lists()
    if upd:
        print(f"已生成原始缺失清单: {upd['path']} (共 {upd['written']} 条)")
    else:
        print("未找到 tools/missing_videos_all.txt，跳过清单生成。")